<?php
namespace Admin\Controller;

use Think\PageAdmin;

/**
 * 教师管理控制器
 */
class TaskController extends BaseController
{

    /**
     * 初始化
     *
     * @return [type] [description]
     */
    public function _initialize()
    {
        parent::_initialize();
    }

    public function index()
    {
        $prefix = C('DB_PREFIX');

        $count = M('task')->count();
        $page  = new PageAdmin($count, C('PAGE_NUM'));

        $pages['show']  = $page->show(); //分页输出
        $pages['total'] = $count; //总数
        $pages['lists'] = M('task a')
            ->order("a.id desc")
            ->limit($page->firstRow . ',' . $page->listRows)
            ->select();

        $this->seotitle = '任务列表';
        $this->pages    = $pages;
        $this->display();
    }

    /**
     * 添加页面
     */
    public function add()
    {
        $info = $this->getProject();
        $this->seotitle = "添加任务";
        $this->assign('info', $info);
        $this->display();
    }

    /**
     * 保存
     * @return [type] [description]
     */
    public function save()
    {
        $action = I('get.action', '', 'trim');
        $params = I('post.');

        if ($params['name'] == '') {
            $this->error('请输入任务主题');
        }

        // if (!session()['user_id']) {
        //     $this->error('请先登录后台！');
        // }

        if ($params['end_time'] == '') {
            $this->error('请输入任务时间');
        }

        if ($params['project_id'] == '0') {
            $this->error('请选择项目');
        }

        $file = M('files')->where(['file_id' => $params['headimg']])->find();
        if ($file) {
            $file_path = C('DOMAIN') . $file['filepath'];
        } else {
            $file_path = $params['headimg'];
        }

        // 新增
        if ($action == 'add') {
            M('task')->add([
                'name'           => trim($params['name']),
                'end_time'       => strtotime($params['end_time']),
                'project_id'     => $params['project_id'],
                'project_name'   => $params['project_name'],
                // 前后台登陆逻辑不一样
                // 'input_user_id'  => session()['user_id'],
                'follow_user_id' => implode(',', $params['follow_user_id']),
                'cc_user_id'     => implode(',', $params['cc_user_id']),
                'remark'         => $params['remark'],
                'status'         => 2,
                'add_time'       => time(),
                //'update_time'     => time()
            ]);

            $this->success('操作成功', U('index'));
        }

        // 编辑保存
        elseif ($action == 'edit') {
            $id = I('post.task_id', 0, 'intval');
            //高级管理员才能进行编辑
            // $tmp = M('user')->where(['id'=>session()['user_id'],'role'=>1])->find();
            // if(!$tmp)
            //     $this->error('高级管理员才能进行编辑！');
                 
            if(!$params['status'])
                $params['status'] = 2;

            $tmpArr = [1,2,3,4];
            if(!in_array($params['status'],$tmpArr))
                $this->error('请填写正确的状态编号！');

            M('task')->where(['id' => $id])->save([
                'name'           => trim($params['name']),
                'end_time'       => strtotime($params['end_time']),
                'project_id'     => $params['project_id'],
                'project_name'   => $params['project_name'],
                // 'input_user_id'  => session()['user_id'],
                'status'         => 2,
                'follow_user_id' => implode(',', $params['follow_user_id']),
                'cc_user_id'     => implode(',', $params['cc_user_id']),
                'remark'         => $params['remark'],
                'update_time'    => time(),
                'status'    => $params['status']
            ]);

            $this->success('操作成功', U('index'));
        }
    }

    public function edit()
    {
        $id = I('get.id', 0, 'intval');
        if (empty($id) ||
            !$info = M('task')->where(['id' => $id])->find()) {
            $this->error('参数错误');
        }

        $project        = $this->getProject();
        $this->seotitle = '任务编辑';
        $this->info     = $info;
        $this->project  = $project;
        $this->display();
    }

    public function delete()
    {
        $id = I('get.id', 0, 'intval');
        M('task')->where(['id' => $id])->delete();
        $this->success('操作成功');
    }

    /**
     * 批量上传excel文件读取数据插入数据库
     * @return [type] [description]
     */
    public function upFile()
    {
        $upload = new \Think\Upload(); // 实例化上传类
        $path   = geturl() . '/Public/excel/';

        $upload->maxSize  = 3145728; // 设置附件上传大小
        $upload->exts     = array('xls'); // 设置附件上传类型
        $upload->rootPath = $path; // 设置附件上传根目录
        $upload->savePath = ''; // 设置附件上传（子）目录

        if (!is_dir($path)) {
            mkdir($path, 2770, true);
        }

        // 上传文件
        $info = $upload->upload();
        if ($info) {
            $url  = $info['file']['savepath'] . $info['file']['savename'];
            $file = $path . $url;
            $res  = $this->readExcelData($file);
            $tmp  = [];
            foreach ($res as $k => $v) {
                if ($v['A'] == '') {
                    $this->error('数据行为空，结束导入');
                }
                $tmp[$k]['sn']             = $v['A']; //编号
                $tmp[$k]['name']           = $v['B']; //名称
                $tmp[$k]['project_id']     = $v['C']; //所属项目id
                $tmp[$k]['follow_user_id'] = $v['D']; //跟进人
                $tmp[$k]['cc_user_id']     = $v['E']; //抄送人
                $tmp[$k]['end_time']       = strtotime($v['F']); //截止时间
                $tmp[$k]['remark']         = $v['G']; //备注
                $tmp[$k]['project_name']   = $this->findProject($tmp[$k]['project_id']); //项目名称
                //$tmp[$k]['input_user_id']  = 1;

                try {
                    $where['sn'] = $tmp[$k]['sn'];
                    $rs          = M('task')->where($where)->find();
                    if ($rs) {
                        //导入编号已存在！进行更新
                        $tmp[$k]['update_time'] = time();
                        $r1                     = M('task')->where($where)->save($tmp[$k]);
                        if (!$r1) {
                            $this->success('更新数据失败');
                        }

                    } else {
                        $tmp[$k]['add_time'] = time();
                        $r2                  = M("task")->add($tmp[$k]);
                        if (!$r2) {
                            $this->success('插入数据失败');
                        }

                    }
                } catch (\Exception $e) {
                    $this->error($e->getMessage());
                }
            }

            $this->success('导入成功', U('index'));

        } else {
            $this->error($upload->getError());
        }
    }

    /**
     * 读取excel数据
     * @param  [type]  $file  [description]
     * @param  integer $types [description]
     * @return [type]         [description]
     */
    public function readExcelData($file, $types = 0)
    {
        // 判断文件是什么格式
        $type      = pathinfo($file);
        $extension = strtolower($type["extension"]);
        $type      = $type === 'csv' ? $type : 'Excel5';
        ini_set('max_execution_time', '0');
        Vendor('PHPExcel.PHPExcel');

        $start_timeAA = microtime(true);
        // 判断使用哪种格式
        $objReader   = \PHPExcel_IOFactory::createReader($type);
        $objPHPExcel = $objReader->load($file);
        //获取工作表的数目
        $sheetCount = $objPHPExcel->getSheetCount();
        $sheet      = $objPHPExcel->getSheet(0);
        // 取得总行数
        $highestRow = $sheet->getHighestRow();
        // 取得总列数
        $highestColumn = $sheet->getHighestColumn();

        if ($types == 1) {
            $highestColumn = 'Z';
        }
        //循环读取excel文件,读取一条,插入一条
        $data = array();
        //从第一行开始读取数据
        for ($j = 2; $j <= $highestRow; $j++) {
            //从A列读取数据
            for ($k = 'A'; $k <= $highestColumn; $k++) {
                $tmp = $objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue();
                // 读取单元格
                $data[$j][$k] = $tmp;
                if ($k == 'F') {
                    //对时间处理，不然会转换为浮点数
                    $data[$j][$k] = gmdate('Y-m-d H:i:s', intval(($tmp - 25569) * 3600 * 24));
                }
            }
        }
        return $data;
    }

    /**
     * 根据id字符串返回项目名称
     * @param  [type] $str [description]
     * @return [type]      [description]
     */
    public function findProject($str)
    {
        $arr = explode('|', $str);
        $ret = '';
        foreach ($arr as $key => $value) {
            $name = '';
            $rs1  = M('project')->where('id=' . $value)->find();
            if ($rs1 && $rs1['pid']) {
                $name .= $rs1['classname'] . ',';
                $rs2 = M('project')->where('id=' . $rs1['pid'])->find();
                if ($rs2 && $rs2['pid']) {
                    $name .= $rs2['classname'] . ',';
                    $rs3 = M('project')->where('id=' . $rs2['pid'])->find();
                    if ($rs3) {
                        $name .= $rs3['classname'];
                    }
                } else {
                    $name .= $rs2['classname'];
                }
            } else {
                $name .= $rs1['classname'];
            }

            $tmp = explode(',', $name);
            $tmp = array_reverse($tmp);
            $tmp = implode(',', $tmp);
            $ret .= $tmp . '|';
        }

        $ret = substr($ret, 0, strlen($ret) - 1);
        return $ret;
    }

    /**
     * 获取项目
     * @return [type] [description]
     */
    public function getProject()
    {
        $project = M("project")->where(['pid' => 0])->field('id,classname value')->select();
        foreach ($project as $k => $v) {
            $child = M("project")->where(['pid' => $v['id']])->field('id,classname value')->select();
            foreach ($child as $key1 => $value1) {
                $child[$key1]['title'] = $v['value'] . ',' . $value1['value'];
            }

            $project[$k]['childs'] = $child;
            $project[$k]['title']  = $v['value'];
            foreach ($child as $key => $value) {
                $childs = M("project")->where(['pid' => $value['id']])->field('id,classname value')->select();
                foreach ($childs as $key2 => $value2) {
                    $childs[$key2]['title'] = $value['title'] . ',' . $value2['value'];
                }

                $project[$k]['childs'][$key]["childs"] = $childs;
            }
        }

        foreach ($project as $key => $value) {
            $project[$key]['childs'] = array_filter($project[$key]['childs']);
            if ($project[$key]['childs'] && count($project[$key]['childs']) > 0) {
                $project[$key]['flag'] = 1;
            } else {
                $project[$key]['flag'] = 0;
            }
            foreach ($project[$key]['childs'] as $key1 => $value1) {
                if ($project[$key]['childs'][$key1]['childs'] && count($project[$key]['childs'][$key1]['childs']) > 0) {
                    $project[$key]['childs'][$key1]['flag'] = 1;
                } else {
                    $project[$key]['childs'][$key1]['flag'] = 0;
                }
            }
        }

        return $project;
    }
}
